/*
 * Copyright (c) 2006-2020, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2020-05-21     chenhy       the first version
 */
#include <board.h>
#include "mem.h"
#include "i2c.h"

#define M24C64_SLV_ADDR   0xA0
#define M24C64_I2C_BUS    i2c1
#define M24C64_WP_SET()   HAL_GPIO_WritePin(GPIOA, GPIO_PIN_11, GPIO_PIN_SET)
#define M24C64_WP_CLR()   HAL_GPIO_WritePin(GPIOA, GPIO_PIN_11, GPIO_PIN_RESET)
#define M24C64_PAGE_SIZE  32
int32_t fram_write(uint16_t reg, void* pbuf, int32_t size)
{
  int32_t write_size, remain;
  int32_t ret;
  M24C64_WP_CLR();
  remain = size;
  while(1) {
    if(reg % M24C64_PAGE_SIZE) write_size = M24C64_PAGE_SIZE - reg % M24C64_PAGE_SIZE;
    else write_size = M24C64_PAGE_SIZE;
    if(remain <= write_size) write_size = remain;
    ret = i2c_write(&M24C64_I2C_BUS, M24C64_SLV_ADDR, reg, pbuf, write_size, 1);
    if(ret != write_size) break;
    remain -= write_size;
    if(remain == 0) break;
    pbuf += write_size;
    reg += write_size;
    i2c_delay_ms(10);
  }
  M24C64_WP_SET();
  return (size-remain);
}

int32_t fram_read(uint16_t reg, void* pbuf, int32_t size)
{
  int32_t read_size;
  read_size = i2c_read(&M24C64_I2C_BUS, M24C64_SLV_ADDR, reg, pbuf, size, 1);
  return read_size;
}
